package com.huan;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用synchronized代码块
 * @author chenbin78
 * @version 1.0
 * @create_date 2021/4/19 10:26
 */
public class SynchronizedBlock {

    private Map<Integer, Integer> map = new HashMap<>();

    private Integer count = 1;


    public void put() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                map.put(count, count);
                System.out.println(Thread.currentThread().getName() + " put：" + count);
                count ++ ;
                this.notify();
                try {
                    this.wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "执行完毕！");
        }
    }

    public void get() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                Integer integer = map.get(count - 1);
                System.out.println(Thread.currentThread().getName() + " get：" + integer);
                this.notify();
                try {
                    this.wait(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(Thread.currentThread().getName() + "执行完毕！");
    }
}
